<template>
  <div class="home-page">
    <!-- 顶部栏 -->
    <div class="top-bar">
      <img class="avatar" :src="userAvatar" @click="goUserOrLogin" />
      <div class="user-info" @click="goUserOrLogin" style="cursor:pointer;">
        <div class="username">{{ userName }}</div>
        <div class="date">{{ currentDate }}</div>
      </div>
      <div class="ai-btn" @click="goAI">
        <van-icon name="smile-comment-o" />
        <span>问问AI助手</span>
      </div>
    </div>

    <!-- 卡路里目标 -->
    <div class="calorie-card">
      <div class="card-title">卡路里目标</div>
      <div class="progress-bar">
        <div class="progress" :class="{ 'progress-warning': progress >= 60 }" :style="{ width: progress + '%' }"></div>
        <div class="progress-text">{{ intake }}</div>
        <div class="progress-total">/ {{ target }}千卡</div>
      </div>
      <div class="calorie-info">
        <div>
          <div class="label">摄入总量</div>
          <div class="value">{{ intake }}克</div>
        </div>
        <div>
          <div class="label">激活代谢</div>
          <div class="value">{{ burn }}克</div>
        </div>
        <div>
          <div class="label">剩余</div>
          <div class="value">{{ left }}克</div>
        </div>
      </div>
    </div>

    <!-- 三餐卡片 -->
    <div class="meal-cards">
      <div class="meal-card" v-for="(meal, idx) in meals" :key="meal.name" @click="toggleFlip(idx)"
        :class="{ flipped: flippedIndex === idx }">
        <div class="card-inner">
          <div class="card-front">
            <img :src="meal.icon" class="meal-icon" />
            <div class="meal-name">{{ meal.name }}</div>
            <div class="meal-info">
              <span class="info-label">热量：</span><span class="info-value">{{ meal.kcal }}千卡</span>
            </div>
            <div class="meal-info">
              <span class="info-label">重量：</span><span class="info-value">{{ meal.gram }}克</span>
            </div>
          </div>
          <div class="card-back">
            <div class="blur-bg" :style="{ backgroundImage: 'url(' + meal.flipImg + ')' }"></div>
            <div class="flip-text">
              <div v-for="(line, i) in splitTextToTwoLines(meal.flipText)" :key="i">{{ line }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 浏览餐食 -->
    <div class="diet-plan-section">
      <div class="plan-header">
        <div class="plan-title">饮食计划</div>
        <!-- 日历部分 -->
        <div class="calendar-bar-scroll">
          <div class="calendar-bar">
            <div class="calendar-day" v-for="(day, idx) in calendarDays" :key="day.date"
              :class="{ active: idx === selectedDay }" @click="selectDay(idx)">
              <div class="calendar-week">{{ day.week }}</div>
              <div class="calendar-date">{{ day.date }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 均衡膳食推荐卡片 -->
      <div class="balanced-section">
        <div class="balanced-title">均衡膳食</div>
        <div class="balanced-list">
          <div class="balanced-card" v-for="item in getBalancedFoods()" :key="item.name">
            <img :src="item.img" class="balanced-img" />
            <div class="balanced-info">
              <div class="balanced-name">{{ item.name }}</div>
              <div class="balanced-desc">{{ item.desc }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 每日计划打卡清单 -->
      <div class="daily-plan-section">
        <div class="daily-plan-item" v-for="(plan, index) in dailyPlans" :key="plan.id || index"
          :class="{ done: plan.done, feedback: plan.feedbacking }" @click="togglePlanDone(plan, $event)">
          <img :src="plan.img" class="plan-img" v-if="plan.img" />
          <div class="plan-info">
            <div class="plan-name">{{ plan.name }}</div>
            <div class="plan-status">
              <van-icon name="checked" v-if="plan.done" color="#ffb300" />
              <span v-if="plan.done" class="done-text">已完成</span>
              <span v-else class="todo-text">点击打卡</span>
            </div>
          </div>
          <van-icon name="delete" class="delete-btn" v-if="!plan.done" @click.stop="deletePlan(plan)" />
        </div>
        <div class="add-plan-btn">
          <van-button icon="plus" block plain type="primary" @click="showAddPlan = true">添加每日打卡计划</van-button>
        </div>
      </div>
      <!-- 添加计划打卡弹窗 -->
      <van-dialog v-model:show="showAddPlan" title="添加饮食计划" show-cancel-button @confirm="addPlan">
        <van-field v-model="newPlanName" label="计划名称" placeholder="如：每天一杯酸奶" />
        <div style="margin: 5px 130px;">
          <van-uploader v-model="newPlanImgArr" :max-count="1" :after-read="onPlanImgRead" preview-size="60" />
        </div>
      </van-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import breakfastIcon from '../assets/images/早餐.png'
import dinnerIcon from '../assets/images/晚餐.png'
import afternoonIcon from '../assets/images/午餐.png'
import { showToast, showDialog } from 'vant'
import { db, STORES } from '../utils/db'
import { getDailyNutrition, getCalorieGoal, getWeeklyNutrition } from '../utils/nutritionSync'
import { getUserDailyPlans, addDailyPlan, updatePlanStatus, deleteDailyPlan } from '../utils/dailyPlansSync'

const router = useRouter()
const DEFAULT_AVATAR = 'https://img.yzcdn.cn/vant/cat.jpeg'
const userName = ref('请登录')
const userAvatar = ref(DEFAULT_AVATAR)

onMounted(async () => {
  if (localStorage.getItem('isLogin')) {
    try {
      const userEmail = localStorage.getItem('userEmail')
      if (userEmail) {
        const user = await db.get(STORES.USER_LIST, userEmail)
        if (user) {
          userName.value = user.username || '测试用户'
          userAvatar.value = user.avatar || DEFAULT_AVATAR
          return
        }
      }
      
      // 如果无法从数据库获取用户信息，使用本地存储的信息
      const storedUserName = localStorage.getItem('userName')
      userName.value = storedUserName || '测试用户'
    } catch (error) {
      console.error('获取用户信息失败:', error)
      showToast('获取用户信息失败')
    }
  } else {
    userName.value = '请登录'
    userAvatar.value = DEFAULT_AVATAR
  }
})

const goUserOrLogin = () => {
  if (!localStorage.getItem('isLogin')) {
    router.push('/login')
  } else {
    router.push('/user')
  }
}

const goAI = () => {
  router.push({ name: 'ai' })
}

const intake = ref(0)
const target = ref(2000)
const burn = ref(0)
const left = ref(0)
const progress = computed(() => Math.round((intake.value / target.value) * 100))

const meals = ref([
  {
    name: '早餐',
    icon: breakfastIcon,
    flipImg: '/images/早餐饮.png',
    flipText: '元气启幕营养筑基',
    kcal: 0,
    gram: 0
  },
  {
    name: '午餐',
    icon: afternoonIcon,
    flipImg: '/images/午餐2.png',
    flipText: '承转续能活力中坚',
    kcal: 0,
    gram: 0
  },
  {
    name: '晚餐',
    icon: dinnerIcon,
    flipImg: '/images/晚餐2.png',
    flipText: '柔养慢调夜宁身安',
    kcal: 0,
    gram: 0
  }
])

const currentDate = ref('')

const updateDate = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  currentDate.value = `${year}.${month}.${day}`
}

let timer = null

const flippedIndex = ref(-1)
const toggleFlip = (idx) => {
  flippedIndex.value = flippedIndex.value === idx ? -1 : idx
}

function splitTextToTwoLines(text) {
  // 始终分两行，每行4字，不足补空
  if (!text) return ["", ""]
  let line1 = text.slice(0, 4)
  let line2 = text.slice(4, 8)
  if (line1.length < 4) line1 = line1.padEnd(4, ' ')
  if (line2.length < 4) line2 = line2.padEnd(4, ' ')
  return [line1, line2]
}

// 日历数据
const calendarDays = ref([])
const selectedDay = ref(0)

// 添加响应式数据
const dailyPlans = ref([])

// 获取每日计划数据
const getDailyPlans = async () => {
  if (!calendarDays.value.length || selectedDay.value === -1) return []
  const weekDay = getWeekDay(calendarDays.value[selectedDay.value].fullDate)
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return []
  
  try {
    const plans = await getUserDailyPlans(userEmail, weekDay)
    dailyPlans.value = plans
    return plans
  } catch (error) {
    console.error('获取每日计划失败:', error)
    return []
  }
}

// 初始化日历数据
const initCalendarDays = () => {
  const now = new Date()
  const currentDay = now.getDay() || 7 // 将周日的0转换为7
  const monday = new Date(now)
  monday.setDate(now.getDate() - currentDay + 1) // 设置为本周一

  calendarDays.value = Array.from({ length: 7 }, (_, i) => {
    const date = new Date(monday)
    date.setDate(monday.getDate() + i)
    return {
      week: ['一', '二', '三', '四', '五', '六', '日'][i],
      date: formatDate(date),
      fullDate: date
    }
  })

  // 设置当前日期为选中状态
  const today = new Date()
  selectedDay.value = calendarDays.value.findIndex(day => 
    day.fullDate.toDateString() === today.toDateString()
  )
}

// 格式化日期
const formatDate = (date) => {
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${month}.${day}`
}

// 获取均衡膳食数据
const getBalancedFoods = () => {
  if (!calendarDays.value.length || selectedDay.value === -1) return []
  const weekDay = getWeekDay(calendarDays.value[selectedDay.value].fullDate)
  return balancedFoodsMap[weekDay] || []
}

// 均衡膳食推荐（按日期）
const balancedFoodsMap = {
  '周一': [
    { name: '全麦面包', img: new URL('../assets/images/全麦面包.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '煮鸡蛋', img: new URL('../assets/images/egg.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '草莓', img: new URL('../assets/images/草莓.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '荞麦面', img: new URL('../assets/images/荞麦面.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '虾仁豆腐', img: new URL('../assets/images/虾仁豆腐.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '清炒菠菜', img: new URL('../assets/images/清炒菠菜.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '蒸紫薯', img: new URL('../assets/images/蒸紫薯.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '凉拌黄瓜', img: new URL('../assets/images/凉拌黄瓜.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '豆奶', img: new URL('../assets/images/豆奶.jpg', import.meta.url).href, desc: '含有丰富的维生素' }
  ],
  '周二': [
    { name: '蔬菜鸡蛋煎饼', img: new URL('../assets/images/蔬菜鸡蛋煎饼.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '梨', img: new URL('../assets/images/梨.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '糙米饭', img: new URL('../assets/images/糙米饭.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '番茄炖牛腩', img: new URL('../assets/images/番茄炖牛腩.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '苹果', img: new URL('../assets/images/苹果.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '白粥', img: new URL('../assets/images/白粥.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '清炒西兰花', img: new URL('../assets/images/清炒西兰花.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '一小把坚果', img: new URL('../assets/images/坚果.jpg', import.meta.url).href, desc: '含有丰富的维生素' }
  ],
  '周三': [
    { name: '全麦馒头', img: new URL('../assets/images/全麦馒头.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '水煮蛋', img: new URL('../assets/images/煮鸡蛋.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '香蕉', img: new URL('../assets/images/香蕉.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '饺子', img: new URL('../assets/images/饺子.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '清炒白菜', img: new URL('../assets/images/清炒白菜.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '芒果', img: new URL('../assets/images/芒果.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '蒸紫薯', img: new URL('../assets/images/蒸紫薯.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '凉拌莴笋', img: new URL('../assets/images/凉拌莴笋.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '豆奶', img: new URL('../assets/images/豆奶.jpg', import.meta.url).href, desc: '含有丰富的维生素' }
  ],
  '周四': [
    { name: '三明治', img: new URL('../assets/images/三明治.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '草莓', img: new URL('../assets/images/草莓.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '荞麦面', img: new URL('../assets/images/荞麦面.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '虾仁豆腐', img: new URL('../assets/images/虾仁豆腐.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '炒油麦菜', img: new URL('../assets/images/炒油麦菜.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '白粥', img: new URL('../assets/images/白粥.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '清炒胡萝卜', img: new URL('../assets/images/清炒胡萝卜.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '苹果', img: new URL('../assets/images/苹果.jpg', import.meta.url).href, desc: '含有丰富的维生素' }
  ],
  '周五': [
    { name: '灌汤包', img: new URL('../assets/images/灌汤包.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '水煮蛋', img: new URL('../assets/images/煮鸡蛋.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '梨', img: new URL('../assets/images/梨.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '糙米饭', img: new URL('../assets/images/糙米饭.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '清炖排骨', img: new URL('../assets/images/清炖排骨.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '凉拌黄瓜', img: new URL('../assets/images/凉拌黄瓜.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '蒸土豆', img: new URL('../assets/images/蒸土豆.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '豆奶', img: new URL('../assets/images/豆奶.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '香蕉', img: new URL('../assets/images/香蕉.jpg', import.meta.url).href, desc: '含有丰富的维生素' }
  ],
  '周六': [
    { name: '全麦馒头', img: new URL('../assets/images/全麦馒头.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '水煮蛋', img: new URL('../assets/images/煮鸡蛋.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '香蕉', img: new URL('../assets/images/香蕉.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '饺子', img: new URL('../assets/images/饺子.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '清炒白菜', img: new URL('../assets/images/清炒白菜.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '芒果', img: new URL('../assets/images/芒果.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '蒸紫薯', img: new URL('../assets/images/蒸紫薯.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '凉拌莴笋', img: new URL('../assets/images/凉拌莴笋.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '豆奶', img: new URL('../assets/images/豆奶.jpg', import.meta.url).href, desc: '含有丰富的维生素' }
  ],
  '周日': [
    { name: '蔬菜鸡蛋煎饼', img: new URL('../assets/images/蔬菜鸡蛋煎饼.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '梨', img: new URL('../assets/images/梨.jpg', import.meta.url).href, desc: '含有丰富的蛋白质' },
    { name: '糙米饭', img: new URL('../assets/images/糙米饭.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '番茄炖牛腩', img: new URL('../assets/images/番茄炖牛腩.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '苹果', img: new URL('../assets/images/苹果.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '白粥', img: new URL('../assets/images/白粥.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '清炒西兰花', img: new URL('../assets/images/清炒西兰花.jpg', import.meta.url).href, desc: '含有丰富的维生素' },
    { name: '一小把坚果', img: new URL('../assets/images/坚果.jpg', import.meta.url).href, desc: '含有丰富的维生素' }
  ]
}

// 获取当前星期的名称
const getWeekDay = (date) => {
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return weekDays[date.getDay()]
}

// 选择日期
const selectDay = async (idx) => {
  selectedDay.value = idx
  await getDailyPlans() // 切换日期时重新加载数据
}

// 添加计划弹窗
const showAddPlan = ref(false)
const newPlanName = ref('')
const newPlanImgArr = ref([])
const newPlanImg = ref('')
const addPlan = async () => {
  if (!calendarDays.value.length || selectedDay.value === -1) return
  const weekDay = getWeekDay(calendarDays.value[selectedDay.value].fullDate)
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) {
    showToast('请先登录')
    return
  }
  
  if (!newPlanName.value.trim()) {
    showToast('请输入计划名称')
    return
  }

  try {
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    const dateStr = `${year}-${month}-${day}`

    const plan = {
      userEmail,
      date: dateStr,
      weekDay,
      name: newPlanName.value,
      img: newPlanImg.value,
      done: false
    }

    const success = await addDailyPlan(plan)
    if (success) {
      showToast('添加成功')
      newPlanName.value = ''
      newPlanImgArr.value = []
      newPlanImg.value = ''
      showAddPlan.value = false
      await getDailyPlans() // 添加成功后重新加载数据
    } else {
      showToast('添加失败')
    }
  } catch (error) {
    console.error('添加计划失败:', error)
    showToast('添加失败')
  }
}
const onPlanImgRead = (file) => {
  // file.content 为 base64
  if (Array.isArray(file)) file = file[0]
  newPlanImg.value = file.content
}

// 计划项打卡/取消打卡
const togglePlanDone = async (plan, e) => {
  // 如果已经完成，不允许取消
  if (plan.done) {
    showToast('已完成打卡，不可取消')
    return
  }

  // 防误触：检查点击位置是否在打卡区域内
  const target = e.target
  const planItem = target.closest('.daily-plan-item')
  const deleteBtn = target.closest('.delete-btn')
  
  // 如果点击的是删除按钮，不触发打卡
  if (deleteBtn) {
    return
  }

  // 添加确认对话框
  try {
    await new Promise((resolve, reject) => {
      showDialog({
        title: '确认打卡',
        message: '确定要完成这个计划吗？',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonColor: '#7c5dfa',
      }).then(() => {
        resolve()
      }).catch(() => {
        reject()
      })
    })

    const success = await updatePlanStatus(plan.id, true)
    if (success) {
      plan.done = true
      plan.feedbacking = true
      showToast('打卡成功！')
      setTimeout(() => {
        plan.feedbacking = false
      }, 400)
      await getDailyPlans() // 更新状态后重新加载数据
    } else {
      showToast('操作失败')
    }
  } catch (error) {
    if (error) {
      console.error('更新计划状态失败:', error)
      showToast('操作失败')
    }
  }
}

// 删除计划项
const deletePlan = async (plan) => {
  // 如果已经完成，不允许删除
  if (plan.done) {
    showToast('已完成打卡，不可删除')
    return
  }

  try {
    await new Promise((resolve, reject) => {
      showDialog({
        title: '确认删除',
        message: '确定要删除这个计划吗？',
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonColor: '#ff4d4f',
      }).then(() => {
        resolve()
      }).catch(() => {
        reject()
      })
    })

    const success = await deleteDailyPlan(plan.id)
    if (success) {
      showToast('已删除')
      await getDailyPlans() // 删除成功后重新加载数据
    } else {
      showToast('删除失败')
    }
  } catch (error) {
    if (error) {
      console.error('删除计划失败:', error)
      showToast('删除失败')
    }
  }
}

// 加载营养数据
const loadNutritionData = async () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  try {
    const { weekTotal } = await getWeeklyNutrition(userEmail)
    const goal = await getCalorieGoal(userEmail)
    
    // 更新卡路里数据
    intake.value = weekTotal.calories
    target.value = goal
    burn.value = Math.round(goal * 0.2) // 假设基础代谢为目标的20%
    left.value = Math.max(0, goal - weekTotal.calories)
  } catch (error) {
    console.error('加载营养数据失败:', error)
    showToast('加载数据失败')
  }
}

// 加载今日三餐数据
const loadTodayMeals = async () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  try {
    const today = new Date()
    const year = today.getFullYear()
    const month = String(today.getMonth() + 1).padStart(2, '0')
    const day = String(today.getDate()).padStart(2, '0')
    const dateStr = `${year}-${month}-${day}`

    const diaryData = await db.getAll(STORES.DIARY_LIST)
    const todayDiary = diaryData.filter(item => 
      item.userEmail === userEmail && item.date === dateStr
    )

    // 更新三餐数据
    meals.value = meals.value.map(meal => {
      const mealData = todayDiary.filter(item => {
        switch(meal.name) {
          case '早餐':
            return item.mealType === 'breakfast'
          case '午餐':
            return item.mealType === 'lunch'
          case '晚餐':
            return item.mealType === 'dinner'
          default:
            return false
        }
      })

      const total = mealData.reduce((acc, item) => {
        return {
          kcal: acc.kcal + Number(item.calories || 0),
          gram: acc.gram + Number(item.amount || 0)
        }
      }, { kcal: 0, gram: 0 })

      return {
        ...meal,
        kcal: Math.round(total.kcal),
        gram: Math.round(total.gram)
      }
    })
  } catch (error) {
    console.error('加载今日三餐数据失败:', error)
    showToast('加载数据失败')
  }
}

// 监听数据库变化
const setupPlansListener = () => {
  const userEmail = localStorage.getItem('userEmail')
  if (!userEmail) return

  // 每5秒刷新一次数据
  const timer = setInterval(async () => {
    await getDailyPlans()
  }, 5000)
  
  return timer
}

onMounted(async () => {
  updateDate()
  initCalendarDays()
  // 每天凌晨更新一次
  timer = setInterval(updateDate, 24 * 60 * 60 * 1000)
  
  // 初始化数据
  await loadNutritionData()
  await loadTodayMeals() // 加载今日三餐数据
  await getDailyPlans() // 初始化时加载计划数据
  
  // 设置监听器
  const plansTimer = setupPlansListener()
  
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer)
    }
    if (plansTimer) {
      clearInterval(plansTimer)
    }
  })
})
</script>

<style scoped>
.home-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #e9eafc 0%, #e6e6fa 100%);
}

.top-bar {
  display: flex;
  align-items: center;
  padding: 18px 16px 8px 16px;
  background: transparent;
  position: relative;
}

.avatar {
  width: 44px;
  height: 44px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #fff;
  box-shadow: 0 2px 8px #e0e0e0;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.date {
  font-size: 13px;
  color: #aaa;
}

.ai-btn {
  position: absolute;
  top: 16px;
  right: 20px;
  background: #7062c1;
  color: #fff;
  border-radius: 20px;
  padding: 6px 16px 6px 12px;
  font-size: 15px;
  display: flex;
  align-items: center;
  box-shadow: 0 4px 12px rgba(112, 98, 193, 0.2);
  z-index: 10;
  cursor: pointer;
  transition: all 0.3s ease;
}

.ai-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(112, 98, 193, 0.3);
}

.ai-btn .van-icon {
  font-size: 20px;
  margin-right: 6px;
}

.ai-text {
  color: #7c5dfa;
  font-size: 15px;
  margin-left: 4px;
  cursor: pointer;
}

.calorie-card {
  background: #7c5dfa;
  border-radius: 18px;
  margin: 16px;
  padding: 18px 20px 12px 20px;
  color: #fff;
  box-shadow: 0 2px 12px #e0e0e0;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
}

.progress-bar {
  position: relative;
  height: 18px;
  background: #e9eafc;
  border-radius: 9px;
  margin-bottom: 10px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #4CAF50 0%, #8BC34A 100%);
  border-radius: 4px;
  transition: all 0.3s ease;
}

.progress-warning {
  background: linear-gradient(90deg, #ff9800 0%, #ff5722 100%);
}

.progress-text {
  position: absolute;
  left: 12px;
  top: 0;
  font-size: 15px;
  color: #fff;
  line-height: 18px;
  font-weight: bold;
}

.progress-total {
  position: absolute;
  right: 12px;
  top: 0;
  font-size: 13px;
  color: #fff;
  line-height: 18px;
}

.calorie-info {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
}

.calorie-info .label {
  font-size: 12px;
  color: #e9eafc;
}

.calorie-info .value {
  font-size: 15px;
  font-weight: bold;
}

.meal-cards {
  display: flex;
  gap: 20px;
  justify-content: center;
  margin: 28px 0 0 0;
}

.meal-card {
  width: 140px;
  height: 160px;
  perspective: 900px;
  border-radius: 16px;
  box-shadow: 0 2px 12px #e0e0e0;
  background: transparent;
  transition: box-shadow 0.3s, transform 0.2s cubic-bezier(.34, 1.56, .64, 1);
  touch-action: manipulation;
  user-select: none;
  position: relative;
}

.meal-card:active {
  transform: scale(0.96);
  box-shadow: 0 2px 8px #bdbdfc;
}

.meal-card.flipped .card-inner {
  transform: rotateY(180deg);
}

.card-inner {
  width: 100%;
  height: 100%;
  position: relative;
  transition: transform 0.6s cubic-bezier(.4, 2, .6, 1);
  transform-style: preserve-3d;
}

.card-front,
.card-back {
  position: absolute;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #fff;
}

.card-front {
  z-index: 2;
}

.card-back {
  transform: rotateY(180deg);
  background: #f6f6fa;
  justify-content: flex-end;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.blur-bg {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  filter: blur(6px) brightness(0.90);
  z-index: 1;
}

.flip-text {
  position: absolute;
  left: 50%;
  bottom: 18px;
  transform: translateX(-50%);
  z-index: 2;
  font-size: 15px;
  color: #fff;
  font-weight: bold;
  text-align: center;
  letter-spacing: 1px;
  line-height: 1.5;
  padding: 0 10px;
  max-width: 90%;
  display: flex;
  flex-direction: column;
  gap: 2px;
  white-space: pre;
}

.meal-icon {
  width: 54px;
  height: 54px;
  border-radius: 12px;
  margin-bottom: 10px;
  object-fit: cover;
  box-shadow: 0 2px 8px #e0e0e0;
}

.meal-name {
  font-size: 17px;
  font-weight: bold;
  color: #7062c1;
  margin-bottom: 4px;
}

.meal-info {
  font-size: 13px;
  color: #888;
  display: flex;
  gap: 2px;
  margin-bottom: 2px;
}

.info-label {
  color: #aaa;
}

.info-value {
  color: #333;
  font-weight: 500;
}

.diet-plan-section {
  background: linear-gradient(135deg, #e9eafc 0%, #e6e6fa 100%);
  border-radius: 18px;
  margin: 18px 0 0 0;
  padding: 18px 16px 24px 16px;
  box-shadow: 0 2px 8px #e0e0e0;
}

.plan-header {
  margin-bottom: 18px;
}

.plan-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.calendar-bar-scroll {
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  padding: 4px 0;
  margin: 0 -4px;
}

.calendar-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  min-width: 420px;
  padding: 0 4px;
}

.calendar-day {
  background: #fff;
  border-radius: 16px;
  padding: 8px 12px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  min-width: 52px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
}

.calendar-day::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(124, 93, 250, 0.1) 0%, rgba(112, 98, 193, 0.1) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.calendar-day:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.calendar-day:hover::before {
  opacity: 1;
}

.calendar-day.active {
  background: linear-gradient(135deg, #7c5dfa 0%, #7062c1 100%);
  color: #fff;
  border: 2px solid #7c5dfa;
  box-shadow: 0 4px 12px rgba(124, 93, 250, 0.2);
}

.calendar-day.active::before {
  display: none;
}

.calendar-week {
  font-size: 13px;
  color: #888;
  margin-bottom: 2px;
  font-weight: 500;
}

.calendar-day.active .calendar-week {
  color: rgba(255, 255, 255, 0.9);
}

.calendar-date {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.calendar-day.active .calendar-date {
  color: #fff;
}

.balanced-section {
  margin-bottom: 18px;
}

.balanced-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.balanced-list {
  display: flex;
  gap: 12px;
  overflow-x: auto;
}

.balanced-card {
  min-width: 90px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px #f3e7c9;
  padding: 10px 8px 8px 8px;
  text-align: center;
  flex-shrink: 0;
}

.balanced-img {
  width: 48px;
  height: 48px;
  object-fit: contain;
  margin-bottom: 6px;
}

.balanced-name {
  font-size: 15px;
  font-weight: bold;
  color: #333;
}

.balanced-desc {
  font-size: 12px;
  color: #888;
}

.daily-plan-section {
  margin-top: 16px;
}

.daily-plan-item {
  display: flex;
  align-items: center;
  background: linear-gradient(135deg, #fff 0%, #f8f9ff 100%);
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 4px 16px rgba(124, 93, 250, 0.08);
  transition: all 0.3s ease;
  border: 1px solid rgba(124, 93, 250, 0.1);
  position: relative;
  overflow: hidden;
  cursor: pointer;
  user-select: none;
}

.daily-plan-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(to bottom, #7c5dfa, #7062c1);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.daily-plan-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(124, 93, 250, 0.12);
}

.daily-plan-item:hover::before {
  opacity: 1;
}

.daily-plan-item.done {
  background: linear-gradient(135deg, #fff 0%, #fff8f0 100%);
  border-color: rgba(255, 179, 0, 0.2);
  cursor: default;
}

.daily-plan-item.done::before {
  background: linear-gradient(to bottom, #ffb300, #ff8000);
  opacity: 1;
}

.plan-img {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  object-fit: cover;
  margin-right: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  border: 2px solid #fff;
}

.plan-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.plan-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  letter-spacing: 0.3px;
}

.plan-status {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
}

.done-text {
  color: #ffb300;
  font-weight: 500;
}

.todo-text {
  color: #7c5dfa;
  font-weight: 500;
}

.add-plan-btn {
  margin-top: 24px;
}

.add-plan-btn :deep(.van-button) {
  height: 48px;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 600;
  background: linear-gradient(135deg, #7c5dfa 0%, #7062c1 100%);
  border: none;
  color: #fff;
  box-shadow: 0 4px 12px rgba(124, 93, 250, 0.2);
  transition: all 0.3s ease;
}

.add-plan-btn :deep(.van-button:active) {
  transform: translateY(1px);
  box-shadow: 0 2px 8px rgba(124, 93, 250, 0.15);
}

.delete-btn {
  font-size: 20px;
  color: #ff4d4f;
  margin-left: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 8px;
  border-radius: 50%;
  background: rgba(255, 77, 79, 0.1);
  opacity: 0.8;
}

.delete-btn:hover {
  opacity: 1;
  transform: scale(1.1);
}

.daily-plan-item.done .delete-btn {
  display: none;
}

.daily-plan-item.feedback {
  animation: feedback-bounce 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
}

@keyframes feedback-bounce {
  0% {
    transform: scale(1);
  }
  30% {
    transform: scale(1.05);
  }
  60% {
    transform: scale(0.98);
  }
  100% {
    transform: scale(1);
  }
}

/* 弹窗样式优化 */
:deep(.van-dialog) {
  border-radius: 24px;
  overflow: hidden;
}

:deep(.van-dialog__header) {
  padding: 24px 24px 16px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

:deep(.van-dialog__content) {
  padding: 16px 24px 24px;
}

:deep(.van-field) {
  background: #f8f9ff;
  border-radius: 12px;
  padding: 12px 16px;
  margin-bottom: 16px;
}

:deep(.van-field__label) {
  color: #666;
  font-weight: 500;
}

:deep(.van-field__control) {
  color: #333;
  font-size: 15px;
}

:deep(.van-uploader) {
  background: #f8f9ff;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  justify-content: center;
}

:deep(.van-uploader__wrapper) {
  justify-content: center;
}

:deep(.van-uploader__upload) {
  background: #fff;
  border: 2px dashed #7c5dfa;
  border-radius: 12px;
  width: 80px;
  height: 80px;
}

:deep(.van-uploader__upload-icon) {
  color: #7c5dfa;
  font-size: 24px;
}

:deep(.van-dialog__footer) {
  padding: 16px 24px 24px;
}

:deep(.van-dialog__button) {
  font-size: 16px;
  font-weight: 600;
  height: 44px;
  border-radius: 22px;
}

:deep(.van-dialog__confirm) {
  background: linear-gradient(135deg, #7c5dfa 0%, #7062c1 100%);
  border: none;
  color: #fff;
}

:deep(.van-dialog__cancel) {
  color: #666;
  border: 1px solid #ddd;
}
</style>